/*
 * Copyright (c) 2011. c.mueller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.altitude.cimuelle.db;

import de.altitude.cimuelle.coop.CoopGame;
import de.altitude.cimuelle.coop.CoopPlayer;
import de.altitude.cimuelle.coop.CoopPlayerArrayList;
import org.apache.log4j.Logger;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * User: cybernaut
 * Date: 19.08.11
 * Time: 00:12
 */
public class DatabaseCoopData {

    private static final java.sql.Connection conn = new DatabaseConnectionCreator().getCon();

    private static final Logger LOGGER = Logger.getLogger("DatabaseCoopData");

    private static final String sqlInsertInitData = "INSERT INTO `altitude_coop_data` " +
            "(`id`, `port`, `vaporIds`, `leftTeamPlayers`, `rightTeamPlayers`, `leftTeam`, `rightTeam`, `winningTeam`, `map`, `mode`, `baseDestroyedBy`, `turretsDestroyed`, `turretsDamageDone`, `playerDied`, `activePlayer`, `completedInSec`, `timeStart`) VALUES " +
            "(NULL, ?, NULL, NULL, NULL, ?, ?, NULL, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, ?);";

    private static final String sqlUpdateData = "UPDATE `altitude_coop_data` SET " +
            "`vaporIds`=?, `leftTeamPlayers`=?, `rightTeamPlayers`=?, `winningTeam`=?, `baseDestroyedBy`=?, `turretsDestroyed`=?," +
            " `turretsDamageDone`=?, `playerDied`=?, `activePlayer`=?, `completedInSec`=?, `timeEnd`=?" +
            " WHERE port=? AND id=?";

    private static final String sqlUpdateDataCoopPlayers = "UPDATE `altitude_coop_data` SET " +
            "`leftCoopPlayersJavaObject` = ?, `rightCoopPlayersJavaObject` = ? " +
            " WHERE port=? AND id=?";

    private static final String sqlDeleteCoopGame = "DELETE FROM `altitude_coop_data` WHERE id=?";

    private static final String sqlSelectCoopGameById = "SELECT * FROM `altitude_coop_data` WHERE id=?";
    private static final String sqlSelectRankByMapPortOrderTime = "select @rownum:=@rownum+1 rownum, d.* from (SELECT @rownum:=0) r, `altitude_coop_data` d WHERE port = ? AND map = ? AND baseDestroyedBy IS NOT NULL AND `completedInSec` IS NOT NULL order by `completedInSec` asc";
    private static final String sqlSelectRankByMapPortIdOrderTime = "SELECT a.* FROM ( SELECT @rownum:=@rownum+1 rownum, d.* FROM (SELECT @rownum:=0) r, `altitude_coop_data` d WHERE port = ? AND map = ? AND baseDestroyedBy IS NOT NULL AND `completedInSec` IS NOT NULL ORDER BY `completedInSec` ASC ) a WHERE id = ?";

    public static int initialData(CoopGame coopGame) {
        int key = -1;
        synchronized (conn) {
            PreparedStatement pst = null;
            ResultSet keys = null;
            try {
                pst = conn.prepareStatement(sqlInsertInitData, Statement.RETURN_GENERATED_KEYS);
                pst.setString(1, coopGame.getPort());
                pst.setInt(2, coopGame.getLeftTeam());
                pst.setInt(3, coopGame.getRightTeam());
                pst.setString(4, coopGame.getMap().getMap());
                pst.setString(5, coopGame.getMap().getMode().name());
                pst.setTimestamp(6, coopGame.getStart());
                LOGGER.debug(pst);
                pst.executeUpdate();
                keys = pst.getGeneratedKeys();
                keys.next();
                key = keys.getInt(1);
            } catch (SQLException e) {
                LOGGER.error(e, e);
            } finally {
                if (pst != null) {
                    try {
                        pst.close();
                    } catch (SQLException e) {
                        LOGGER.error(e, e);
                    }
                }
                if (keys != null) {
                    try {
                        keys.close();
                    } catch (SQLException e) {
                        LOGGER.error(e, e);
                    }
                }
            }
        }
        return key;
    }

    public static void updateData(CoopGame coopGame) {
        synchronized (conn) {
            PreparedStatement pst = null;
            try {
                pst = conn.prepareStatement(sqlUpdateData);
                pst.setString(1, coopGame.getVaporIds());
                pst.setString(2, coopGame.getLeftTeamPlayers());
                pst.setString(3, coopGame.getRightTeamPlayers());
                pst.setInt(4, coopGame.getWinningTeam());
                pst.setString(5, coopGame.getBaseDestroyedBy());
                pst.setInt(6, coopGame.getGameStats().getTurretsDestroyed());
                pst.setInt(7, coopGame.getGameStats().getTurretsDamageDone());
                pst.setInt(8, coopGame.getGameStats().getPlayerDied());
                pst.setInt(9, coopGame.getGameStats().getActivePlayer());
                pst.setDouble(10, coopGame.getDuration());
                pst.setTimestamp(11, coopGame.getStop());
                pst.setString(12, coopGame.getPort());
                pst.setInt(13, coopGame.getDatabaseId());
                LOGGER.debug(pst);
                pst.executeUpdate();
                updateCoopPlayers(coopGame);
            } catch (SQLException e) {
                e.printStackTrace();
                LOGGER.error(e, e);
            } finally {
                if (pst != null) {
                    try {
                        pst.close();
                    } catch (SQLException e) {
                        LOGGER.error(e, e);
                    }
                }
            }
        }
    }

    private static void updateCoopPlayers(CoopGame coopGame) {
        synchronized (conn) {
            PreparedStatement pst = null;
            try {
                pst = conn.prepareStatement(sqlUpdateDataCoopPlayers);
                List<CoopPlayer> object = coopGame.getLeftTeamPlayersAsList();
                List<CoopPlayer> object2 = coopGame.getRightTeamPlayersAsList();
                pst.setBytes(1, getSerializeObject(object).toByteArray());
                pst.setBytes(2, getSerializeObject(object2).toByteArray());
                pst.setString(3, coopGame.getPort());
                pst.setInt(4, coopGame.getDatabaseId());
                LOGGER.debug(pst);
                pst.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
                LOGGER.error(e, e);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (pst != null) {
                    try {
                        pst.close();
                    } catch (SQLException e) {
                        LOGGER.error(e, e);
                    }
                }
            }
        }
    }

    private static ByteArrayOutputStream getSerializeObject(List<CoopPlayer> object) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oout = new ObjectOutputStream(baos);
        oout.writeObject(object);
        oout.close();
        return baos;
    }

    public static CoopGame getCoopGameById(int databaseId) {
        ResultSet rs = null;
        PreparedStatement pst = null;
        CoopGame coopGame = null;
        try {
            pst = conn.prepareStatement(sqlSelectCoopGameById);
            pst.setInt(1, databaseId);
            LOGGER.debug(pst);
            rs = pst.executeQuery();

            if (rs.next()) {
                coopGame = fillCoopGameFromResult(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        } finally {
            closeConnections(pst, rs);
        }

        return coopGame;
    }

    private static CoopGame fillCoopGameFromResult(ResultSet rs, boolean isRankAvailbale) {
        try {
            int rank;
            if (isRankAvailbale) {
                rank = rs.getInt("rownum");
            } else {
                rank = -1;
            }
            int id = rs.getInt("id");
            String port = rs.getString("port");
            String vapors = rs.getString("vaporIds");
            String leftPlayers = rs.getString("leftTeamPlayers");
            String rightPlayers = rs.getString("rightTeamPlayers");
            int leftTeam = rs.getInt("leftTeam");
            int rightTeam = rs.getInt("rightTeam");
            int winningTeam = rs.getInt("winningTeam");
            String map = rs.getString("map");
            String mode = rs.getString("mode");
            String baseDestroyedBy = rs.getString("baseDestroyedBy");
            int turretsDestroyed = rs.getInt("turretsDestroyed");
            int turretsDamageDone = rs.getInt("turretsDamageDone");
            int playerDied = rs.getInt("playerDied");
            int activePlayer = rs.getInt("activePlayer");
            double duration = rs.getDouble("completedInSec");
            Timestamp start = rs.getTimestamp("timeStart");
            Timestamp stop = rs.getTimestamp("timeEnd");

            Object leftCoopPlayers;
            Object rightCoopPlayers;

            CoopPlayerArrayList left;
            leftCoopPlayers = readObjectFromDB(rs, "leftCoopPlayersJavaObject");
            if (leftCoopPlayers != null) {
                //noinspection unchecked
                left = (CoopPlayerArrayList) leftCoopPlayers;
            } else {
                left = new CoopPlayerArrayList();
            }

            CoopPlayerArrayList right;
            rightCoopPlayers = readObjectFromDB(rs, "rightCoopPlayersJavaObject");
            if (rightCoopPlayers != null) {
                //noinspection unchecked
                right = (CoopPlayerArrayList) rightCoopPlayers;
            } else {
                right = new CoopPlayerArrayList();
            }
            if (vapors != null) {
                return new CoopGame(rank, id, port, vapors, leftPlayers, rightPlayers, leftTeam, rightTeam, winningTeam, map, mode, baseDestroyedBy, turretsDestroyed, turretsDamageDone, playerDied, activePlayer, duration, left, right, start, stop);
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        }
        return null;
    }

    private static Object readObjectFromDB(ResultSet rs, String column) throws SQLException {
        byte[] buf = rs.getBytes(column);
        Object leftCoopPlayers = null;
        if (buf != null) {
            ObjectInputStream objectIn;
            try {
                objectIn = new ObjectInputStream(
                        new ByteArrayInputStream(buf));
                leftCoopPlayers = objectIn.readObject();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return leftCoopPlayers;
    }

    private static void closeConnections(PreparedStatement pst, ResultSet rs) {
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
                LOGGER.debug(e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
                LOGGER.debug(e);
            }
        }
    }

    public static List<CoopGame> getCoopGameRanksByPortMap(String port, String map) {
        ResultSet rs = null;
        PreparedStatement pst = null;
        List<CoopGame> coopGames = new ArrayList<CoopGame>();
        try {
            pst = conn.prepareStatement(sqlSelectRankByMapPortOrderTime);
            pst.setString(1, port);
            pst.setString(2, map);
            LOGGER.debug(pst);
            rs = pst.executeQuery();

            while (rs.next()) {
                coopGames.add(fillCoopGameFromResult(rs, true));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        } finally {
            closeConnections(pst, rs);
        }

        return coopGames;
    }

    private static CoopGame fillCoopGameFromResult(ResultSet rs) {
        return fillCoopGameFromResult(rs, false);
    }

    public static CoopGame getCoopGameRanksByPortMapId(String port, String map, int id) {
        ResultSet rs = null;
        PreparedStatement pst = null;
        CoopGame coopGame = null;
        try {
            pst = conn.prepareStatement(sqlSelectRankByMapPortIdOrderTime);
            pst.setString(1, port);
            pst.setString(2, map);
            pst.setInt(3, id);
            LOGGER.debug(pst);
            rs = pst.executeQuery();

            if (rs.next()) {
                coopGame = fillCoopGameFromResult(rs, true);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error(e, e);
        } finally {
            closeConnections(pst, rs);
        }

        return coopGame;
    }

    public static int getRankByPortMapId(String port, String map, int databaseId) {
        CoopGame coopGame = getCoopGameRanksByPortMapId(port, map, databaseId);
        if (coopGame != null) {
            return coopGame.getRank();
        }
        return -1;
    }

    public static void deleteCoopGame(int databaseId) {
        LOGGER.info("Trying to delete game " + databaseId + ".");
        synchronized (conn) {
            PreparedStatement pst = null;
            try {
                pst = conn.prepareStatement(sqlDeleteCoopGame);
                pst.setInt(1, databaseId);
                LOGGER.debug(pst);
                pst.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
                LOGGER.error(e, e);
            } finally {
                if (pst != null) {
                    try {
                        pst.close();
                    } catch (SQLException e) {
                        LOGGER.error(e, e);
                    }
                }
            }
        }
    }
}
